from rest_framework.views import APIView
from rest_framework.response import Response
from .sers import *
import uuid
from django.db.models import F


class UserView(APIView):

    def get(self, request):

        queryset = User.objects.all()
        ser = UserSer(queryset, many=True)

        return Response(ser.data)

    def post(self, request):
        ser = UserSer(data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({"msg": "注册成功", "code": 200})
        else:
            print(ser.errors)
            return Response({"msg": "注册失败", "code": 400})

    def put(self, request):
        # 升级用户 就是更新用户的level字段

        user_id = request.data.get("user")
        User.objects.filter(id=user_id).update(level=2)

        # 要给该用户 分发两个优惠券
        c1 = Coupon.objects.create(sn=uuid.uuid1().hex, title="满10减5", max=10, discount=5)
        c2 = Coupon.objects.create(sn=uuid.uuid1().hex, title="满20减10", max=20, discount=10)

        UserCoupon.objects.create(user_id=user_id, coupon_id=c1.id)
        UserCoupon.objects.create(user_id=user_id, coupon_id=c2.id)

        return Response({"msg": "更新操作", "code": 200})


class GoodsView(APIView):

    def get(self, request):
        queryset = Goods.objects.all()
        ser = GoodsSer(queryset, many=True)
        return Response(ser.data)


class CartView(APIView):

    def get(self, request):
        uid = request.GET.get("user")
        queryset = Cart.objects.filter(user_id=uid)

        ser = CartListSer(queryset, many=True)

        return Response(ser.data)

    def post(self, request):
        ser = CartSer(data=request.data)

        if ser.is_valid():
            cart = ser.save()
            # 减库存
            Goods.objects.filter(id=cart.goods_id).update(stock=F("stock") - 1)
            return Response({"msg": "添加购物车成功", "code": 200})
        else:
            print(ser.errors)
            return Response({"msg": "添加购物车成功", "code": 200})


class CouponView(APIView):

    def get(self, request):
        uid = request.GET.get("user")
        queryset = UserCoupon.objects.filter(user_id=uid,)
        ser = UserCouponSer(queryset, many=True)

        return Response(ser.data)


